// pages/specific/specific.js
var that;
var config = require("../comm/Config.js");
var Util = require('../comm/util.js');
var mIamgeUrl = "";
var mVideoUrl = "";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    loadhidden: false,
    loadText: "加载中....",
    toasthidden: true,
    toastText: "传入的参数不正确。",
    datas: [],
    imageUrl: mIamgeUrl,
    videoUrl: mVideoUrl,
    modalHidden:true

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    if (options == null || options.publishTime == null
      || options.publishTime.split("-").length != 3) {
      this.setData({
        loadhidden: true,
        toasthidden: false,
        toastText: "参数不正确"
      });
      return;
    }
    let time = options.publishTime;
    time = Util.replaceAll(time, '-', '/');
    // time.split('-').join('/')
    requestData(that, time);
  },
  toastChanger: function (rst) {
    debugger
    this.setData({ toasthidden: true });
  },
  onImageClick: function (rst) {
    that.setData({
      modalHidden: false
    });
  },
  onSaveClick:function(res){
    saveImage();
  },
  onCancelClick:function(res){
    that.setData({
      modalHidden:true
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  }
});

function requestData(that, time) {
  wx.request({
    url: config.BASE_URL + "/history/content/day/" + time,
    method: 'GET',
    header: {
      'Content-Type': 'application/json'
    },
    success: function (res) {
      debugger
      if (res == null ||
        res.data == null ||
        res.data.results == null ||
        res.data.results.length <= 0) {
        console.error(Constant.ERROR_DATA_IS_NULL);
        that.setData({
          loadhidden: true,
          toasthidden: false,
          toastText: Constant.ERROR_DATA_IS_NULL
        });
        return;
      }
      parseHtml(res.data.results[0].content);
    },
    fail: function (rst) {
      debugger
      that.setData({
        loadhidden: true,
        toasthidden: false,
        toastText: Constant.ERROR_DATA_IS_NULL
      });
    }
  });
};

function saveImage(){
  that.setData({
    loadhidden:false,
    loadText:"下载中...",
    toasthidden:true,
    modalHidden:true
  })
  wx.downloadFile({
    url: mIamgeUrl,
    success:function(res){
      console.log("download success");
      debugger;
      if (res.statusCode === 200) {
        //保存到本地文件
        wx.saveFile({
          tempFilePath: res.tempFilePath,
          success: function (res) {
            var savedFilePath = res.savedFilePath
            that.setData({
              loadhidden: true,
              toasthidden:false,
              toastText:"保存成功"
            })
          }
        });
        
        return ;
      }
      that.setData({
        loadhidden: true,
        toasthidden: false,
      })
    },
    fail:function(res){
      that.setData({
        loadhidden: true,
        toasthidden: false,
      })
    }
  })


}

function parseHtml(htmlBlock) {
  //这边图片的URL解析同main.js中
  var re = new RegExp("[a-zA-z]+://[^\"]*");
  var title = htmlBlock.split("img alt=")[1].match(re)[0];

  if (-1 != title.search("//ww")) {
    mIamgeUrl = title.replace("//ww", "//ws");
  } else {
    mIamgeUrl = title;
  }

  var tags = [];
  var items = [];

  var doc = Util.parseHtml(htmlBlock);
  var tagElements = doc.getElementsByTagName("ul");
  // console.log(doc);
  console.log(tagElements);
  var i = 0;
  for (; i < tagElements.length; i++) {
    var value = tagElements[i];
    if (value.innerText.trim().length == 0) {
      continue;
    }
    var valueChildren = value.children;
    var j = 0;
    var singleItems = [];
    for (; j < valueChildren.length; j++) {
      var singleItem = [];
      singleItem.push(valueChildren[j].innerText.trim());
      singleItem.push(valueChildren[j].children[0].href.trim());
      singleItems.push(singleItem);
    }
    items.push(singleItems);
  }

  var h3s = doc.getElementsByTagName("h3");
  var i = 0;
  for (; i < h3s.length; i++) {
    tags.push(h3s[i].innerText);
  }

  if (tags.length != items.length) {
    console.log("not right");
  }

  var finalData = [];

  var i = 0;
  for (; i < tags.length; i++) {
    var node = [];
    node.push(tags[i]);
    node.push(items[i]);
    finalData.push(node);
  }

  //将获得的各种数据写入itemList，用于setData
  var itemList = [];
  for (var i = 0; i < tags.length; i++) {
    var singleItemList = [];
    for (var j = 0; j < items[i].length; j++) {
      singleItemList.push({ title: items[i][j][0], url: items[i][j][1] });
      if (i == tags.length - 1) {
        mVideoUrl = items[i][j][1];
      }
    }
    itemList.push({ tag: tags[i], singleItems: singleItemList });
  }

  that.setData({
    datas: itemList,
    imageUrl: mIamgeUrl,
    videoUrl: mVideoUrl,
    loadhidden: true
  });
  console.log(finalData);
}